/*
 * 文 件 名:  BaseActionSupport.java
 * 版    权:  Huawei Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  lKF34018
 * 修改时间:  2013-10-14
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.kuanrf.common.base;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;
import com.kuanrf.common.util.PropertyUtils;

/**
 * action公用父类可以用来提取session ，request,response等
 * 
 * @author  pWX14772
 * @version  [版本号, 2009-9-24]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class BaseActionSupport extends ActionSupport implements SessionAware,
        ApplicationAware, ServletContextAware, ServletRequestAware,
        ServletResponseAware
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -3507308732331831135L;
    
    private Map<String, Object> session;
    
    private ServletContext servletContext;
    
    private HttpServletRequest servletRequest;
    
    private HttpServletResponse servletResponse;
    
    private Map<String, Object> application;
    
    protected String successMessage;
    
    protected String errorMessage;
    
    protected String returnUrl = "";
    
    /**
     * ajax请求操作的结果
     */
    protected String ajaxResult = "success";
    
    protected String html = "";
    
    /**
     * 允许的主机名
     */
    private Set<String> hostNames = new HashSet<String>(100);
    
    /**
     * <默认构造函数>
     */
    public BaseActionSupport()
    {
        //从配置文件中得到允许上传文件的服务器地址
        String hostName = PropertyUtils.getValue("upload.domain.filter");
        if (hostName != null && hostName.trim().length() > 0)
        {
            hostNames.addAll(Arrays.asList(hostName.split(",")));
        }
        try
        {
            //循环得到本机IP
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements())
            {
                NetworkInterface networkInterface = enumeration.nextElement();
                if (networkInterface.isUp())
                {
                    Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
                    while (addressEnumeration.hasMoreElements())
                    {
                        InetAddress addr = addressEnumeration.nextElement();
                        String ip = addr.getHostAddress().toString();
                        if (ip != null)
                        {
                            hostNames.add(ip);
                        }
                        hostName = addr.getHostName().toString();
                        if (hostName != null)
                        {
                            hostNames.add(hostName);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            
        }
    }
    
    /**
     * 检查Request中请求的Header是否合法
     * <功能详细描述> [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    protected boolean checkRequestHeader()
    {
        HttpServletRequest request = this.getServletRequest();
        //得到跳转过来之前的页面
        String header = request.getHeader("Referer");
        if (header == null)
        {
            return true;
        }
        //得到请求的主机名
        String host = null;
        try
        {
            URL url = new URL(header);
            host = url.getHost();
        }
        catch (MalformedURLException e)
        {
            return false;
        }
        Pattern pattern = null;
        String host_ = null;
        boolean rs_ = false;
        Iterator<String> iterator = hostNames.iterator();
        //检查过来的请求Host是否合法
        while (iterator.hasNext())
        {
            host_ = iterator.next();
            pattern = Pattern.compile(host_);
            Matcher mat = pattern.matcher(host);
            rs_ = mat.find();
            if (rs_)
            {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查Request中请求的Header是否合法
     * <功能详细描述> [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    protected boolean checkRemoteIpAddr()
    {
        //得到请求的主机名
        String host = this.getIpAddr(getServletRequest());
        if (host == null)
        {
            return true;
        }
        Pattern pattern = null;
        String host_ = null;
        boolean rs_ = false;
        Iterator<String> iterator = hostNames.iterator();
        //检查过来的请求Host是否合法
        while (iterator.hasNext())
        {
            host_ = iterator.next();
            pattern = Pattern.compile(host_);
            Matcher mat = pattern.matcher(host);
            rs_ = mat.find();
            if (rs_)
            {
                return true;
            }
        }
        return false;
    }
    
    /**
     * @return 返回 session
     */
    public Map<String, Object> getSession()
    {
        return session;
    }
    
    /**
     * @param 对session进行赋值
     */
    public void setSession(Map<String, Object> session)
    {
        this.session = session;
    }
    
    /**
     * @return 返回 servletContext
     */
    public ServletContext getServletContext()
    {
        return servletContext;
    }
    
    /**
     * @param 对servletContext进行赋值
     */
    public void setServletContext(ServletContext servletContext)
    {
        this.servletContext = servletContext;
    }
    
    /**
     * @return 返回 servletRequest
     */
    public HttpServletRequest getServletRequest()
    {
        return servletRequest;
    }
    
    /**
     * @param 对servletRequest进行赋值
     */
    public void setServletRequest(HttpServletRequest servletRequest)
    {
        this.servletRequest = servletRequest;
    }
    
    /**
     * @return 返回 servletResponse
     */
    public HttpServletResponse getServletResponse()
    {
        return servletResponse;
    }
    
    /**
     * @param 对servletResponse进行赋值
     */
    public void setServletResponse(HttpServletResponse servletResponse)
    {
        servletResponse.setContentType("text/html;charset=gbk");
        this.servletResponse = servletResponse;
    }
    
    /**
     * @return 返回 application
     */
    public Map<String, Object> getApplication()
    {
        return application;
    }
    
    /**
     * @param 对application进行赋值
     */
    public void setApplication(Map<String, Object> application)
    {
        this.application = application;
    }
    
    /**
     * 得到客户端IP
     * <功能详细描述>
     * @param request
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public String getIpAddr(HttpServletRequest request)
    {
        String clientIp = request.getHeader("x-forwarded-for");
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp)))
        {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp)))
        {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp)))
        {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }
    
    // 根据Map输出JSON，返回null
    public String ajaxJson(Map<String, String> jsonMap)
    {
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "text/html");
    }
    
    /**
     * 
     */
    public String ajax(String content, String type)
    {
        try
        {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            //解决跨域无法访问的问题
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.getWriter().write(content);
            response.getWriter().flush();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String getSuccessMessage()
    {
        return successMessage;
    }
    
    public void setSuccessMessage(String successMessage)
    {
        this.successMessage = successMessage;
    }
    
    public String getErrorMessage()
    {
        return errorMessage;
    }
    
    public void setErrorMessage(String errorMessage)
    {
        this.errorMessage = errorMessage;
    }
    
    public String getReturnUrl()
    {
        return returnUrl;
    }
    
    public void setReturnUrl(String returnUrl)
    {
        this.returnUrl = returnUrl;
    }
    
    public String getAjaxResult()
    {
        return ajaxResult;
    }
    
    public void setAjaxResult(String ajaxResult)
    {
        this.ajaxResult = ajaxResult;
    }
    
    public String getHtml()
    {
        return html;
    }
    
    public void setHtml(String html)
    {
        this.html = html;
    }
    
}
